package bTree.LeetCode;

import javax.swing.tree.TreeNode;
import java.util.LinkedList;
import java.util.Queue;

public class 反转二叉树的奇数层 {
    public TreeNode reverseOddLevels(TreeNode root) {
        Queue<TreeNode>queue=new LinkedList<>();
        queue.add(root);
        int cnt=0;
        while (!queue.isEmpty()){
            int size = queue.size();
            TreeNode[] treeNodes = new TreeNode[size];
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left!=null){
                    queue.add(poll.left);
                }
                if (poll.right!=null){
                    queue.add(poll.right);
                }
                treeNodes[i]=poll;
            }
            if (cnt%2==1){
                reversal(treeNodes);
            }
            cnt++;
        }
        return root;
    }

    private void reversal(TreeNode[] treeNodes) {
        int length = treeNodes.length;
        int left=0;
        int right=length-1;
        while (left<right){
            TreeNode tLeft = treeNodes[left];
            TreeNode tRight = treeNodes[right];
            int left1=tLeft.val;
            int right1=tRight.val;
            int temp=left1;
            tLeft.val=right1;
            tRight.val=temp;
            left++;
            right--;
        }
    }
}